<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { message } from "ant-design-vue";
  import { BasicDrawer, useDrawerInner, BasicForm, useForm } from '@gui-pkg/antdcomponents';
  import { formSchema } from './config.data';
  import {addStationData, addtargetData} from '@/api/alerts/warningConfig';

  const isUpdate = ref(true);
  const emit = defineEmits(['success', 'register']);
  const configId = ref('');

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      configId.value = data.record.id;
      let target =  data.record.target.split(",");
      setFieldsValue({
        ...data.record,
        "targets":target
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增配置' : '编辑配置'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      // 向后台提交菜单数据
      if (unref(isUpdate)) {
        await addtargetData({...values, id: unref(configId)});
        message.success('编辑成功');
      } else {
        await addtargetData(values);
        message.success('新增成功');
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" rel="stylesheet/less" scoped>

</style>
